<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/22
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\user;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;


/**
 * 优惠券💶
 * @Auth(name="token",nologin={"get_coupons_list","get_coupons_data","get_goods_coupons_list"})
 * @Controller("/user.coupons/")
 */
class Coupons extends UserBean
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];


    /**
     * 领取优惠券
     * @param integer $coupons_id 用户优惠券
     * @return void
     * @Action
     */
    public function get_coupons($coupons_id = null)
    {
        $coupons = $this->getCoupon($coupons_id);
        if ($coupons['stock'] < 1) {
            $this->error('该优惠券库存不足');
        }
        if ($coupons['status'] != 'up') {
            return $this->error('不能领取');
        }
        switch ($coupons['type_status']) {
            case '1':
                //类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷

                break;

            case '6':
                //类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷
                if (date('n') > 10) {
                    return $this->error('该商品优惠券,只能在1-10号内领取');
                }
                break;
            default:
                # code...
                break;
        }

        $data['user_id'] = $this->auth->user()->id;
        $data['coupons_id'] = $coupons_id;

        $count = Db::name('user_coupons')->whereEx($data)->count();
        if ($count >= $coupons['limit']) {
            return $this->error('该优惠券限制每人' . $coupons['limit'] . '张');
            var_dump('该优惠券限制每人' . $coupons_id);
        }


        // 状态:up=上架,halt=暂停,down=下架
        switch ($coupons['status']) {
            case 'up':
                break;
            case 'halt':
                return $this->error('该优惠券限制暂不能领取');
                break;
            case 'down':
                return $this->error('该优惠券已下架');
                break;
            default:
                # code...
                break;
        }

        $data['createtime'] = time();
        // $data['end_time'] = $coupons['usetime']; //需要修改
        if ($coupons['s'] > 0) {
            $end_time = time() + $coupons['s'];
        } else {
            $end_time = $coupons['usetimeend'];
        }
        $data['end_time'] = $end_time;
        $data['store_id'] = $coupons['store_id'];
        $data['status'] = '1';
        $data['get_status'] = '1'; //获取状态:1=领取,2=发放,3=转赠
        Db::name('user_coupons')->insert($data);
        //减少库存
        Db::name('coupons')->where('id', '=', $coupons_id)->setFieldDec('stock', 1)->update();
        return $this->success('领取成功');
    }




    /**
     * 获取最大的店铺优惠券
     *
     * @param int $goods_money 商品总价格
     * @param int $store_id 店铺id
     * @return void
     * @Action
     */
    public function get_max_store_coupon($goods_money = 0, ?int $store_id)
    {
        var_dump($goods_money, $this->auth->user()->id, $store_id);
        $coupon = $this->getMaxStoreCoupon($goods_money, $this->auth->user()->id, $store_id);
        return $this->success($goods_money, $coupon);
    }


    /**
     * 获取最大的平台优惠券
     *
     * @param int $goods_money 商品总价格
     * @return void
     * @Action
     */
    public function get_max_coupon($goods_money)
    {
        $coupon = $this->getMaxCoupon($goods_money, $this->auth->user()->id);
        return $this->success($goods_money, $coupon);
    }

    /**
     * 获取优惠券列表💶
     *
     * @param string $date 年月(可不传
     * @param integer $page 1
     * @param integer $limit 10
     * @param integer $store_id 店铺
     * @return void
     * @Action
     */
    public function get_coupons_list(?int $page = 1, ?int  $limit = 10, $date = null, ?int $store_id = null, $store_type = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data = [];
        if ($date) {
            $date = date('Y-m', strtotime($date));
            $e_date = date('Y-m-d 23:59:59', strtotime($date . " +1 month -1 day"));
            $data['createtime'] = ['between time', [$date, $e_date]];
        }
        if ($store_id || $store_id === 0) {
            $data['store_id'] = $store_id;
        }
        // $data['user_id'] = $this->auth->user()->id;             
        $data['get_status'] = '2'; //都可以领取
        $data['status'] = 'up'; //状态:up=上架,halt=暂停,down=下架
        $list = Db::name('coupons')->whereEx($data)->whereIsNull('deletetime')->where('get_status', '=', '2')->where('type_status', 'in', ['1', '6'])->orderRaw('createtime desc')->page($page, $limit)->select()->getArray();
        if ($list)
            foreach ($list as $key => &$val) {
                $this->ChangeFieldData($val);
                if ($val['goods_ids'] > 0) {
                    $val['goods'] = $this->GetGoodsShortDataById4($val['goods_ids']);
                }
                //我已经领取的数量
                $val['me_num'] = Db::name('user_coupons')->where('coupons_id', '=', $val['id'])->where('user_id', '=', $this->auth->user()->id)->count();
            }
        return $this->success('ok', $list);
    }


    /**
     * 获取商品优惠券列表💶
     *
     * @param string $date 年月(可不传
     * @param integer $page 1
     * @param integer $limit 10
     * @param integer $goods_id 商品id
     * @return void
     * @Action
     */
    public function get_goods_coupons_list(?int $page = 1, ?int  $limit = 10, $date = null, ?int $goods_id = null, $store_type = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data = [];
        if ($date) {
            $date = date('Y-m', strtotime($date));
            $e_date = date('Y-m-d 23:59:59', strtotime($date . " +1 month -1 day"));
            $data['createtime'] = ['between time', [$date, $e_date]];
        }

        if ($goods_id) {
            $data['goods_ids'] = $goods_id;
        } else {
            return $this->error('请传递商品id', $goods_id);
        }
        // $data['user_id'] = $this->auth->user()->id;             
        $data['get_status'] = '2'; //都可以领取
        $data['status'] = 'up'; //状态:up=上架,halt=暂停,down=下架
        $list = Db::name('coupons')
            ->whereEx($data)
            ->whereIsNull('deletetime')
            ->where('get_status', '=', '2')
            ->where('type_status', 'in', ['1', '6'])
            ->orderRaw('createtime desc')
            ->page($page, $limit)
            ->select()
            ->getArray();
        if ($list)
            foreach ($list as $key => &$val) {
                $this->ChangeFieldData($val);
                //我已经领取的数量
                $val['me_num'] = Db::name('user_coupons')->where('coupons_id', '=', $val['id'])->where('user_id', '=', $this->auth->user()->id)->count();
            }
        return $this->success('ok', $list);
    }




    /**
     * 获取店铺分享优惠券💶
     *
     * @param integer $store_id 店铺
     * @return void
     * @Action
     */
    public function get_store_share_coupons(?int $store_id = null)
    {

        if ($store_id || $store_id === 0) {
            $data['store_id'] = $store_id;
        }
        // $data['user_id'] = $this->auth->user()->id;             
        $data['get_status'] = '2'; //都可以领取
        $val = Db::name('coupons')->whereEx($data)->whereIsNull('deletetime')->where('status', '=', 'up')->where('type_status', '=', '3')->orderRaw('createtime desc')->find();

        if ($val)
            $this->ChangeFieldData($val);

        return $this->success('ok', $val);
    }


    /**
     * 获取优惠券详情💶
     *
     * @param int $id 签到id
     * @return void
     * @Action
     */
    public function get_coupons_data($id = null)
    {

        $data['id'] = $id;
        // $data['user_id'] = $this->auth->user()->id;
        $res = Db::name('coupons')->whereEx($data)->whereIsNull('deletetime')->find();
        if (!$res) {
            return $this->error('没有该优惠券');
        }
        $this->ChangeFieldData($res);
        return $this->success('ok', $res);
    }

    /**
     * 赠送优惠券给谁💶
     *
     * @param int $id id
     * @return void
     * @Action
     */
    public function give_coupons($id, $user_id = null)
    {
        $data['id'] = $id;
        $data['user_id'] = $this->auth->user()->id;
        $res = Db::name('user_coupons')->whereEx($data)->find();
        if (!$res) {
            return $this->error('没有该优惠券');
        }

        if ($res['status'] == '1') {
            return $this->error('非待使用,不能赠送');
        }

        if ($res['get_status'] == '3') {
            return $this->error('转赠的优惠券,不能再转赠');
        }

        $coupons = $this->getCoupon($res['coupons_id']);
        if ($coupons['give_status'] != '2') {
            //赠送:1=不支持,2=支持
            return $this->error('该优惠券不支持转赠');
        }
        //新建一个 把原来的优惠券复制一份

        $new['user_id'] = $user_id;
        $new['get_status'] = '3'; //获取状态:1=领取,2=发放,3=转赠
        $new['give_user_id'] = $this->auth->user()->id;
        $new['store_id'] = $res['store_id']; //店铺ID
        $new['end_time'] = $res['end_time']; //到期时间
        $new['createtime'] = time();

        $new['usetime'] = $res['usetime'];
        $new['order_id'] = $res['order_id'];
        $new['coupons_id'] = $res['coupons_id'];
        $new['order_id'] = $res['order_id'];
        $new['status'] = $res['status'];
        $insert_id = Db::name('user_coupons')->insert($new)->getLastInsertId();

        if ($insert_id) {
            Db::name('user_coupons')->where('id', '=', $id)->update(['status' => '4', 'new_id' => $insert_id]);
            return $this->success('转赠成功');
        }


        // Db::name('user_coupons')->where('id', '=', $id)->update(['user_id' => $user_id, 'get_status' => '3', 'give_user_id' => $this->auth->user()->id]);
        return $this->error('未知错误');
    }

    /**
     * 获取用户信息
     *
     * @param int $user_id 用户id
     * @return void
     */
    public function get_user_data($user_id)
    {
        $user = Db::name('name')->where('id', '=', $user_id)->find();
        if ($user) {
            return $this->success('ok', $user);
        }
        return $this->error('没有');
    }




    /**
     * 获取我的优惠券列表💶
     *
     * @param string $date 年月(可不传
     * @param integer $page 1
     * @param integer $limit 10
     * @param integer $store_id 店铺传0是平台券
     * @param integer $goods_id 商品id
     * @param string $status 状态:1=待使用,2=已使用,3=已过期,4=已赠送
     * @param string $store_type 1平台,2店铺
     * @param string $scene 使用场景current=通用,auction=拍卖,groupon=拼团,rice=米市,direct=直接付,scan=扫码付
     * @param string $scene_type 场景类型:默认current=通用,auction_server=拍卖服务费
     * @return void 
     * @Action
     */
    public function get_my_coupons_list(?string $store_type = null, ?int $page = 1, ?int  $limit = 10, $date = null, ?int $store_id = null, $goods_id = null, ?string $status = null, ?string $scene = null, ?string $scene_type = "current")
    {

        $this->判断优惠券过期列表($this->auth->user()->id);
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $scene_type = $scene_type ?: "current";

        $data = [];
        if ($date) {
            $date = date('Y-m', strtotime($date));
            $e_date = date('Y-m-d 23:59:59', strtotime($date . " +1 month -1 day"));
            $data['createtime'] = ['between time', [$date, $e_date]];
        }
        if ($goods_id)
            $data['goods_ids'] = $goods_id;
        

        if ($scene) {
            $coupons_ids = Db::name('coupons')
                ->where('scene', 'in', explode(',', $scene))
                ->where('scene_type','=',$scene_type)
                ->where('type_status', '!=', '4') //'类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷',
                ->column('id');
            $data['coupons_id'] = ['in', $coupons_ids];
        }

        $store_str = '';
        if ($store_type == '1') {
            // $store_id = 0;
            // $data['store_id'] = $store_id;
            $store_str = 'store_id = 0';
        } elseif ($store_type == '2') {

            if ($store_id > 0) {
                // $data['store_id'] = $store_id;
                $store_str = 'store_id = ' . $store_id;
            } else {
                $store_str = 'store_id > 0';
                // $data['store_id'] = ['>','0'];
            }
        }

        if ($status) {
            $data['status'] = $status;
            if ($status == '3') { // 过期时间一个月内
                $data['end_time'] = ['>', time() - 86400 * 30];
            }
        }


        $data['user_id'] = $this->auth->user()->id;
        $list = Db::name('user_coupons')->whereEx($data)->orderRaw('createtime desc')->whereRaw($store_str)->page($page, $limit)->select()->getArray();
        if ($list)
            foreach ($list as $key => &$val) {
                $this->ChangeUserCouponsFieldData($val);
            }
        return $this->success('ok', $list);
    }

    public function 判断优惠券过期列表($user_id)
    {
        // $data['user_id'] = $user_id;
        //状态:1=待使用,2=已使用,3=已过期,4=已赠送
        $list = Db::name('user_coupons')
            ->where('user_id', '=', $user_id)
            ->where('status', '=', '1')
            ->where('end_time', '>', 1)
            ->where('end_time', '<', time())
            ->update(['status' => '3']);
    }



    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeUserCouponsFieldData(&$val)
    {
        $val['coupons'] = Db::name('coupons')->where('id', '=', $val['coupons_id'])->find();
        $val['date_str'] = $this->TimeToStr($val['createtime']);
        $val['end_date'] = date('Y-m-d H:i:s', $val['end_time']);
        if ($val['store_id'] > 0)
            $val['store'] = Db::name('store')->where('id', '=', $val['store_id'])->find();
        switch ($val['status']) {
            case '4': //赠送给谁了
                $whom_data = Db::name('user_coupons')->where('id', '=', $val['new_id'])->find();
                $val['whom_user'] = $this->GetUserData1($whom_data['user_id']);
                break;

            default:
                # code...
                break;
        }


        if ($val['coupons']['usetimestart'] > 0)
            $val['coupons']['usedate_start'] = date('Y-m-d', $val['coupons']['usetimestart']);
        if ($val['coupons']['usetimeend'] > 0)
            $val['coupons']['usedate_end'] = date('Y-m-d', $val['coupons']['usetimeend']);

        if ($val['coupons']['goods_ids'] > 0) {
            $val['goods'] = $this->GetGoodsShortDataById4($val['coupons']['goods_ids']);
            var_dump($val['goods']);
        }

        return $val;
    }



    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldData(&$val)
    {
        $val['date_str'] = $this->TimeToStr($val['createtime']);
        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        if ($val['store_id'] > 0)
            $val['store'] = Db::name('store')->where('id', '=', $val['store_id'])->find();

        if ($val['usetimestart'] > 0)
            $val['usedate_start'] = date('Y-m-d', $val['usetimestart']);
        if ($val['usetimeend'] > 0)
            $val['usedate_end'] = date('Y-m-d', $val['usetimeend']);
        return $val;
    }
}
